package com.whately.core.base.fileupload.qiniu;


import com.whately.core.base.exception.ServiceException;
import com.whately.core.base.fileupload.qiniu.util.ImageInfoVo;
import com.whately.core.base.fileupload.qiniu.util.ImagesHelper;
import com.whately.core.base.fileupload.qiniu.util.UploadFileAbsolutePathUtil;
import com.whately.core.base.fileupload.vo.UploadFileRespVO;
import com.whately.core.base.fileupload.vo.UploadFileWithBucketBO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件上传
 */
@Component
@Slf4j
public class QiNiuFileUploadHelper {

    @Autowired
    private QiNiuFileUploadProxy qiNiuFileUploadProxy;

    /**
     * 单图片上传服务接口
     */
    public UploadFileRespVO uploadFileRevertFullPath(UploadFileWithBucketBO uploadFileWithBucketBO) {
        try {
            MultipartFile file = uploadFileWithBucketBO.getFile();
            String bucket = uploadFileWithBucketBO.getBucket();
            ImageInfoVo imageInfoVo = qiNiuFileUploadProxy.uploadFile( file, bucket);
            String relativeUrl = ImagesHelper.appendVersionToRelationUrlInfo(imageInfoVo.fetchRelativePath());
            String fullUrl = UploadFileAbsolutePathUtil.singleGetAbsoluteUrlWithWidthAndHeight(relativeUrl);
            UploadFileRespVO vo = new UploadFileRespVO();
            vo.setFullUrl(fullUrl);
            vo.setRelativeUrl(relativeUrl);
            return vo;
        } catch (Exception e) {
            log.info("upload file fail.", e);
            throw new ServiceException(400,"上传文件失败");
        }
    }

}
